package com.digitalchina.lxnsy.activity.old;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ccj.poptabview.FilterConfig;
import com.ccj.poptabview.PopTabView;
import com.ccj.poptabview.base.BaseFilterTabBean;
import com.ccj.poptabview.bean.FilterGroup;
import com.ccj.poptabview.bean.FilterTabBean;
import com.ccj.poptabview.listener.OnPopTabSetListener;
import com.ccj.poptabview.loader.PopEntityLoaderImp;
import com.ccj.poptabview.loader.ResultLoaderImp;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessTechnologies;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.SearchTypeVO;
import com.digitalchina.lxnsy.entity.ShareFarmListVO;
import com.digitalchina.lxnsy.entity.ShareFarmTypeVO;
import com.digitalchina.lxnsy.entity.TechnologiesVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.viewholder.TechnologiesListHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/1/10 16:20
 * 修改备注：
 * ================================================
 */
public class TechnologiesListActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, OnPopTabSetListener {

    @Bind(R.id.expand_pop)
    PopTabView expandPop;
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.tv_search)
    EditText tvSearch;
    @Bind(R.id.iv_cancel)
    ImageView ivCancel;

    private RecyclerArrayAdapter adapter;

    private int page = 1;
    private int limit = 10;
    private List<TechnologiesVO> voList = new ArrayList<>();
    private String keywords = "";
    private String eClassCode = "";
    private String sortType = "";
    // 分类
    private List<SearchTypeVO> list = new ArrayList<>();


    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_technologies_list);
        setTitle("技术大全列表");
    }

    @Override
    public void initMember() {

        // 产品分类
        BusinessTechnologies.primaryClassificationByTechnogy(this, mHandler);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new TechnologiesListHolder(parent);
            }
        });

        onRefresh();
    }

    @Override
    protected void onResume() {
        super.onResume();

        page = 1;
        BusinessTechnologies.technologyList(this, page, limit, keywords, eClassCode, sortType,"1", mHandler);

    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                GotoUtil.gotoActivity(TechnologiesListActivity.this, TechnologiesDetailActivity.class, "TechnologiesVO", adapter.getAllData().get(position));
            }
        });

        tvSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) textView
                            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(), 0);
                    }
                    // 刷新列表数据
                    if (!keywords.equals(tvSearch.getText().toString())) {
                        keywords = tvSearch.getText().toString();
                        eClassCode = "";
                        sortType = "";
                        expandPop.setDefaultLabel();
                        onRefresh();
                    }
                    return true;
                }
                return false;
            }
        });


        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                keywords = "";
                eClassCode = "";
                sortType = "";
                tvSearch.setText("");
                expandPop.setDefaultLabel();


                onRefresh();
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (recyclerView == null)
                    return;

                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);
                switch (msg.what) {
                    case MSG.MSG_TECHNOLOGIES_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_TECHNOLOGIES_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_TECHNOLOGIES_TYPE_SUCCESS:
                        setType(msg.obj);
                        break;
                    case MSG.MSG_TECHNOLOGIES_TYPE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    private void setType(Object object) {
        list = FastJsonUtil.getListBeanRow(object.toString(),"options", SearchTypeVO.class);

        if (list != null && list.size() > 0) {

            SearchTypeVO vo = new SearchTypeVO();
            vo.setLabel("全部");
            vo.setValue("");
            list.add(0, vo);

            FilterGroup filterGroup2 = getMyData2();
            FilterGroup filterGroup3 = getMyData3();

            expandPop.setOnPopTabSetListener(this)
                    .setPopEntityLoader(new PopEntityLoaderImp()).setResultLoader(new ResultLoaderImp()); //配置 {筛选类型}  方式
            expandPop.addFilterItem(filterGroup2.getTab_group_name(), filterGroup2.getFilter_tab(), filterGroup2.getTab_group_type(), filterGroup2.getSingle_or_mutiply());
            expandPop.addFilterItem(filterGroup3.getTab_group_name(), filterGroup3.getFilter_tab(), filterGroup3.getTab_group_type(), filterGroup3.getSingle_or_mutiply());

        }

    }

    /**
     * 设置第二组筛选器
     *
     * @return
     */
    public FilterGroup getMyData2() {

        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("技术分类");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_SINGLE);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);


        List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            // 一级filter
            FilterTabBean singleFilterBean = new FilterTabBean();
            singleFilterBean.setTab_id(list.get(i).getValue());
            singleFilterBean.setTab_name(list.get(i).getLabel());
            singleFilterList.add(singleFilterBean);
        }

        filterGroup.setFilter_tab(singleFilterList);
        return filterGroup;

    }

    /**
     * 设置第三组筛选器
     * 0--推荐分类  1--最新  2--最热
     *
     * @return
     */
    public FilterGroup getMyData3() {

        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("默认排序");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_SINGLE);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);


        List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

        String array[] = {"最新", "最热"};
        FilterTabBean singleFilterBean1 = new FilterTabBean();
        singleFilterBean1.setTab_id("");
        singleFilterBean1.setTab_name("默认排序");
        singleFilterList.add(singleFilterBean1);
        for (int i = 0; i < array.length; i++) {//一级filter
            FilterTabBean singleFilterBean = new FilterTabBean();
            singleFilterBean.setTab_id(i + "");
            singleFilterBean.setTab_name(array[i]);
            singleFilterList.add(singleFilterBean);
        }

        filterGroup.setFilter_tab(singleFilterList);
        return filterGroup;

    }

    @Override
    public void callBack(Object object) {
        voList = FastJsonUtil.getListBeanRow(object.toString(), "rows", TechnologiesVO.class);

        if (page == 1) { // 刷新
            adapter.clear();
        }

        adapter.addAll(voList);

        if (voList != null) {
            if (voList.size() < limit) {
                adapter.stopMore();
            }
        }


    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onRefresh() {
        /**
         * 技术大全列表
         *
         * @param keywords    关键字
         * @param eClassCode  专家三级分类
         * @param rDirectCode 专家领域分类
         * @param sortType    排序类型 ： 空 or 0--推荐分类  1--最新  2--最热
         * @param page        页码
         * @param limit       条数
         */
        page = 1;
        BusinessTechnologies.technologyList(this, page, limit, keywords, eClassCode, sortType,"1", mHandler);
    }

    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= limit) {
            page++;
            BusinessTechnologies.technologyList(this, page, limit, keywords, eClassCode, sortType,"1", mHandler);
        }
    }

    @Override
    public void onPopTabSet(int index, String label, Object params, String value) {
        keywords = "";
        tvSearch.setText("");
        switch (index) {
            case 0:
                eClassCode = params + "";
                break;
            case 1:
                sortType = params + "";
                break;
        }
        onRefresh();
    }
}
